package scenarios.gui.actions;

import dht.node.DHTNodeRow;
import scenarios.net.TestNode;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by IntelliJ IDEA.
 * User: gvennet
 * Date: 21.02.2010
 * Time: 14:38:36
 */
public class WriteTopology extends AbstractAction
{
	ArrayList<TestNode> nodes;
	ScheduledThreadPoolExecutor scheduledExecutor;
	JToggleButton topButton;
	String prStr;


	public WriteTopology(ArrayList<TestNode> nodes, ScheduledThreadPoolExecutor scheduledExecutor, JToggleButton topButton)
	{
		super("Топология");
		this.nodes = nodes;
		this.scheduledExecutor = scheduledExecutor;
		this.topButton = topButton;
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (topButton.isSelected())
		{
			scheduledExecutor.scheduleAtFixedRate(new WriteFile(), 0, 1, TimeUnit.MICROSECONDS);
		}
		else
		{
			scheduledExecutor.shutdownNow();
		}
	}

	private class WriteFile implements Runnable
	{
		WriteFile()
		{

		}

		public void run()
		{
			ArrayList<TestNode> tempCopy = new ArrayList<TestNode>(nodes);

			String body = "";

			for (int i = 0; i < tempCopy.size(); i++)
			{
				body = body + "\"" + tempCopy.get(i).getId().toString() + "\"" + " [label=\"node" + i + "\"]\n";
			}
			for (TestNode node : tempCopy)
			{
				for (DHTNodeRow row : node.getNodeModel().getNodes())
				{
					if (node.getId().compareTo(row.getId()) != 0)
					{
						body = body + "\"" + node.getId().toString() + "\"" + "->" + "\"" + row.getId().toString() + "\"\n";
					}
				}
			}

			body = "digraph g {\n" + body + "}";

			if (!body.equals(prStr))
			{
				FileWriter fileWriter = null;
				try
				{
					fileWriter = new FileWriter("/Users/gvennet/dots/" + System.currentTimeMillis() + ".dot");
				}
				catch (IOException e1)
				{
					e1.printStackTrace();
				}
				try
				{
					fileWriter.write(body);
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
				try
				{
					fileWriter.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}

			prStr = body;
		}
	}
}